package cn.wk.basic.service.impl;

import cn.wk.basic.constant.ConstantVerification;
import cn.wk.basic.exception.DiyException;
import cn.wk.basic.service.IVerificationCodeService;
import cn.wk.basic.utils.SendMsg_webchinese;
import cn.wk.basic.utils.StrUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {
    //注入redis
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 注册发送验证码
     * @param phone
     * @throws DiyException
     * @throws IOException
     */
    @Override
    public void sendMobileCode(String phone) throws DiyException, IOException {
        sendCodeUtil(phone,ConstantVerification.USE_REG);
    }

    /**
     * 微信绑定发送验证码
     * @param phone
     * @throws DiyException
     * @throws IOException
     */
    @Override
    public void sendCode(String phone) throws DiyException, IOException {
        sendCodeUtil(phone,ConstantVerification.USE_BINDER);
    }

    /**
     * 发送验证码
     * @param phone 手机号
     * @param info  是登录还是注册还什么状态
     * @throws DiyException
     */
    public void sendCodeUtil(String phone,String info) throws DiyException {
        //后台产生随机4位验证码
        String complexRandomString = StrUtils.getComplexRandomString(4);
        //为redis准备key值
        String key = phone +":"+ info;
        //五分钟内要发送同样的验证码，但是一分钟内不能多次请求
        //拿出redis中的验证码
        String code = (String)redisTemplate.opsForValue().get(key);
        //判断是否有值，有值的话就说明5分钟还没结束
        if(!StringUtils.isEmpty(code)){
            //拿出数据中的时间戳
            String[] split = code.split(":");
            //然后判断是否超过一分钟
            if(System.currentTimeMillis()-Long.valueOf(split[1]) <= 60*1000){
                throw new DiyException("一分钟内请勿多次发送验证码");
            }
            //这里还是5分钟以内，把redis中的值重新赋值给验证码
            complexRandomString = split[0];
        }
        //把产生的验证码设置到redis中去,给redis设置个存活时间5分钟
        redisTemplate.opsForValue().set(key,
                complexRandomString+":"+System.currentTimeMillis(), 5,TimeUnit.MINUTES);
        //发送验证码
        System.out.println(complexRandomString);
        String context = "输入验证码："+complexRandomString;
        SendMsg_webchinese.send(phone,context);
    }

}
